//
//  GYBluetoothViewController.m
//  LockManagement
//
//  Created by apple on 2018/7/24.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYBluetoothViewController.h"
#import "GYBleOperationManager.h"
#import "GYDeviceTableViewCell.h"
#import "GYBleDataManager.h"
#import "GYBleCeshiViewController.h"
#import "GYSpeechSynthesizerTool.h"
#import "GYKey.h"

@interface GYBluetoothViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UILabel *BLEsearchLable;
@property (weak, nonatomic) IBOutlet UITableView *searchResultTableView;

/** 蓝牙操作对象 */
@property (nonatomic, strong) GYBleOperationManager *bleOperationManager;

/** 发现设备 */
@property (nonatomic, strong) NSMutableArray *foundDevices;

/** 缓存用户设备列表中的设备名字 */
@property (nonatomic, strong) NSMutableDictionary *cachesDeviceName;

/** 缓存用户设备列表中的设备mac地址 */
@property (nonatomic, strong) NSMutableDictionary *cachesDeviceMAC;

/** 得到缓存中的钥匙列表 */
@property (nonatomic, strong) NSArray *cachesKeys;


@end

@implementation GYBluetoothViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(bleReceiveMessage:) name:BLEReceeiveMessage object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BLEReceeiveMessage object:nil];
}

- (void)bleReceiveMessage:(NSNotification *)noti {
    //解析收到的数据
    NSData *messageData = noti.object;
    NSLog(@"receiveMessage==========%@ ===============%lu",noti.object,(unsigned long)messageData.length);
    
    //1.取得命令编号 判断是那条命令
    NSData *headData = [messageData subdataWithRange:NSMakeRange(2, 1)];
    int title = [[GYBleDataManager convertDataToHexStr:headData] intValue];
    
//    //2.去除内容
//    NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
    
    if (title == 7) {
        //2.去除内容
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"SDtt6789" iv:nil error:nil];
        NSLog(@"bindKey   7=========%@",decryptData);
        int successed = [[GYBleDataManager convertDataToHexStr:decryptData] intValue];
        if (successed == 1) {
            NSLog(@"绑定蓝牙钥匙成功========然后发送查询蓝牙钥匙电量的命令");
            NSData *elcData = [GYBleDataManager getKeyElc];
            [self sendMessageData:elcData];
        }
    }else if (title == 6) {
        //2.去除内容
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *elcdata = [messageData subdataWithRange:NSMakeRange(5, 1)];//钥匙的电量
        
        //        NSData *mauData = [messageData subdataWithRange:NSMakeRange(6, 1)];//厂家
        //        NSData *verData = [messageData subdataWithRange:NSMakeRange(7, 2)];//版本号
        //        NSData *desData = [messageData subdataWithRange:NSMakeRange(9, 1)];//加密方式
        NSLog(@"蓝牙查询电量命令成功=========%%%@",[GYBleDataManager convertDataToHexStr:elcdata]);
        
        //发送蓝牙钥匙校时的命令
        NSData *schoolTimeData = [GYBleDataManager schoolTimeToKey];
        [self sendMessageData:schoolTimeData];
    }else if (title == 12) {
        //2.去除内容
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_345" iv:nil error:nil];
        int successed = [[GYBleDataManager convertDataToHexStr:decryptData] intValue];
        if (successed == 1) {
            NSLog(@"蓝牙钥匙校时成功========");
            [SVProgressHUD showSuccessWithStatus:@"蓝牙初始化成功!"];
            [self dismissViewControllerAnimated:YES completion:nil];
            
            
            //发送锁上传日志的命令 (每次连接成功之后必须要发送日志连接成功)
            NSData *uploadLogData = [GYBleDataManager uploadLockLog];
            [self sendMessageData:uploadLogData];
        }else {
            [SVProgressHUD showSuccessWithStatus:@"蓝牙初始化失败!"];
        }
    }else if (title == 2) {
        NSLog(@"接收到初始化门锁信息的  返回");
        //2.去除内容
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"SDtt6789" iv:nil error:nil];
        int type = [[GYBleDataManager convertDataToHexStr:decryptData] intValue];
        if (type == 1) {
            NSLog(@"初始化锁具成功==========");
            [SVProgressHUD showSuccessWithStatus:@"蓝牙初始化成功!"];
        }else if (type == 2) {
            [SVProgressHUD showSuccessWithStatus:@"蓝牙初始化成功!"];
            NSLog(@"锁具已安装,不允许修改初始秘钥");
        }
    }else if (title == 14) {
        NSLog(@"收到锁上传日志........");
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSLog(@"contentData=============%@",contentData);
    }
}

- (void)setupUI {
    
    self.searchResultTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.BLEsearchLable.layer.cornerRadius = 65;
    self.BLEsearchLable.layer.borderWidth = 1;
    self.BLEsearchLable.layer.borderColor = BackGroundColor.CGColor;
    
    //给lable添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(beginSearchBLE:)];
    [self.BLEsearchLable addGestureRecognizer:tap];
    
    //首先判断蓝牙的状态是开还是关
    if (self.bleOperationManager.centerMnaager.state == CBCentralManagerStatePoweredOn) {
        //在判断是不是连接上设备
        if (self.bleOperationManager.connectType == deviceConntTypeSuccess) {
            self.BLEsearchLable.text = @"连接中";
        }
    }
    
    [self listerDeviceState];
    
#warning 创建按钮 跳转测试界面
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-60, 36, 40, 30)];
//    [btn setTitle:@"测试" forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(ceshiBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btn];
}

/**
 返回按钮点击事件

 @param sender <#sender description#>
 */
- (IBAction)backBtnClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)ceshiBtnClick {
    GYBleCeshiViewController *ceshiController = [[GYBleCeshiViewController alloc] initWithNibName:@"GYBleCeshiViewController" bundle:nil];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:ceshiController];
    [self presentViewController:navi animated:YES completion:nil];
}


- (void)listerDeviceState {
    
    //监听蓝牙的状态
    kWeakSelf(self)
    self.bleOperationManager.blueManagerStateChangedCallBack = ^(CBCentralManager *centerMnaager, CBManagerState state) {
        if (state == CBCentralManagerStatePoweredOff) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"打开蓝牙允许 锁群管理 连接到配件" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *setAaction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:SystemVersion < 10.0 ? @"prefs:root=Bluetooth" :  @"App-Prefs:root=Bluetooth"];
                if ([[UIApplication sharedApplication] canOpenURL:url])
                {
                    
                    [[UIApplication sharedApplication] openURL:url];
                }
            }];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:nil];
            
            [alertController addAction:setAaction];
            [alertController addAction:cancelAction];
            
            [weakself presentViewController:alertController animated:YES completion:nil];
            
        }
    };
    
    //监听设备扫描到的服务
    self.bleOperationManager.blueManagerSearchDeviceServiceCallBack = ^(CBPeripheral *periphreal, NSArray<CBService *> *serviceArray, NSError *error) {
        NSLog(@"设备成功检索到服务.....");
        for (CBService *tempService in serviceArray) {
            if ([tempService.UUID.UUIDString isEqualToString:serviceUUID]) {
                
                //1.扫描特征
                [periphreal discoverCharacteristics:nil forService:tempService];
                break;
            }
        }
    };
}

/**
 开始蓝牙搜索

 @param tapGR <#sender description#>
 */
- (void)beginSearchBLE:(UITapGestureRecognizer *)tapGR {
    if (self.bleOperationManager.connectType == deviceConntTypeSuccess) {
        
        [self.bleOperationManager disConnectDevice];
        self.BLEsearchLable.text = @"开始搜索";
        
        return;
    }
    self.BLEsearchLable.text = @"搜索中";
    //1.清空原来数据
    [self.foundDevices removeAllObjects];
    
    kWeakSelf(self)
    [self.bleOperationManager scanDeviceWithCallback:^(CBPeripheral *peripheral, searchFlagType searchType) {
        switch (searchType) {
            case searchFlagTypeAdded:
            {
                //这里要判断是否显示搜索到的设备
                //NSLog(@"macAddress======%@",peripheral.identifier.UUIDString);
                if (peripheral.name.length == 0 || peripheral.name.length < 12) {
                    return ;
                }
                //1.首先获取程序中缓存的钥匙
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    for (GYKey *key in weakself.cachesKeys) {
                        //处理钥匙mac地址 并且比较
                        NSArray *macArray = [key.keyMac componentsSeparatedByString:@":"];
                        NSString *macString = @"";
                        for (NSString *st in macArray) {
                            macString = [macString stringByAppendingString:st];
                        }
                        //NSLog(@"peripheral.name========%@",peripheral.name);
                        NSString *deviceMacString = [peripheral.name substringWithRange:NSMakeRange(peripheral.name.length-12, 12)];
                        if ([macString isEqualToString:deviceMacString]) {
                            
                            //代表用户设备列表中有这个设备 (添加到数据 在缓存mac地址 和类表中的名字)
                            [weakself.foundDevices addObject:peripheral];
                            [weakself.cachesDeviceMAC setObject:key.keyMac forKey:peripheral.identifier.UUIDString];
                            [weakself.cachesDeviceName setObject:key.keyName forKey:peripheral.identifier.UUIDString];
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakself.searchResultTableView reloadData];
                            });
                            
                            break;
                        }
                    }
                });
            }
                break;
                
            case searchFlagTypeFinish:
            {
                [SVProgressHUD showWithStatus:@"扫描设备超时!"];
                [SVProgressHUD dismissWithDelay:2];
            }
                break;
                
            default:
                break;
        }
    }];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.foundDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYDeviceTableViewCell *cell = [GYDeviceTableViewCell cellWithTableview:tableView];
    
    CBPeripheral *periphreal = self.foundDevices[indexPath.row];
    cell.deviceNameLable.text = [self.cachesDeviceName objectForKey:periphreal.identifier.UUIDString];
    cell.deviceMacAddressLable.text = [self.cachesDeviceMAC objectForKey:periphreal.identifier.UUIDString];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CBPeripheral *connectPeriphreal = self.foundDevices[indexPath.row];
    kWeakSelf(self)
    [self.bleOperationManager connectDevice:connectPeriphreal withTimeOut:0.5 options:nil callBack:^(CBPeripheral *periphreal, NSError *error, deviceConnectType deviceConnectType) {
        switch (deviceConnectType) {
            case deviceConntTypeSuccess:
                {
//                    [SVProgressHUD showSuccessWithStatus:@"连接设备成功!"];
                    
                    //文字转换成语音播报
                    GYSpeechSynthesizerTool *tool = [[GYSpeechSynthesizerTool alloc] init];
                    [tool textToSpeechConversion:@"钥匙链接成功"];
                    
                    //设备应该停止扫描
                    [weakself.bleOperationManager stopScanDevice];
                    
                    weakself.BLEsearchLable.text = @"连接成功";
#warning 当蓝牙设备连接成功,1.绑定蓝牙钥匙
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        NSLog(@"0.5秒之后发送数据....");
                        //给钥匙发送校时
//                        NSData *schooLTimeToKeyData = [GYBleDataManager schoolTimeToKey];
//                        [self sendMessageData:schooLTimeToKeyData];
                        //绑定钥匙
                        NSData *bindKeyData = [GYBleDataManager bindBleKey];
                        [self sendMessageData:bindKeyData];
                    });
                    
                    
                }
                break;
                
            case deviceConntTypeFailed:
            {
                [SVProgressHUD showErrorWithStatus:@"连接失败!"];
            }
                break;
                
            default:
                break;
        }
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}


#pragma 蓝牙的发送数据 处理方法 --- 这个蓝牙收发最多只能20字节,超过20字节的需要自己分段  分成20字节一段开始发送

/**
 针对蓝牙发送的数据做一个分包处理

 @param messageData <#messageData description#>
 */
- (void)sendMessageData:(NSData *)messageData {
    if (messageData.length > 20) {
        NSData *contentData;
        int count = messageData.length/20 + 1;
        
        Byte *testByte =(Byte *)[messageData bytes];
        for (int i = 0; i < count; i++) {
            Byte ceshi[20] = {0};
            for (int k=0; k < 20; k++) {
                ceshi[k] = testByte[i*20+k];
            }
            NSData *ceshiData = [NSData dataWithBytes:ceshi length:20];
            [self.bleOperationManager sendMessage:ceshiData];
            [NSThread sleepForTimeInterval:0.01];
        }
    }else {
        [self.bleOperationManager sendMessage:messageData];
    }
}

#pragma mark -- 懒加载

- (GYBleOperationManager *)bleOperationManager {
    if (!_bleOperationManager) {
        _bleOperationManager = [GYBleOperationManager shareOperationManager];
    }
    
    return _bleOperationManager;
}

- (NSMutableArray *)foundDevices {
    if (!_foundDevices) {
        _foundDevices = [NSMutableArray array];
    }
    
    return _foundDevices;
}

- (NSMutableDictionary *)cachesDeviceName {
    if (!_cachesDeviceName) {
        _cachesDeviceName = [NSMutableDictionary dictionary];
    }
    
    return _cachesDeviceName;
}

- (NSMutableDictionary *)cachesDeviceMAC {
    if (!_cachesDeviceMAC) {
        _cachesDeviceMAC = [NSMutableDictionary dictionary];
    }
    
    return _cachesDeviceMAC;
}

- (NSArray *)cachesKeys {
    if (!_cachesKeys) {
        _cachesKeys = [GYKey getCachesKeys];
    }
    
    return _cachesKeys;
}










@end
